package com.example.concurrentprogramming8016.ReentrantReadWriteLock;

import java.util.HashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author liyanhao
 * @Date 2023-01-07 15:01
 */
public class Cache {
    static HashMap<String, Object> hashMap = new HashMap<String, Object>();
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private static Lock readlock = reentrantReadWriteLock.readLock();
    private static Lock writelock = reentrantReadWriteLock.writeLock();

    //获取一个key对应的value
    public static final Object get(String key) {
        readlock.lock();
        try {
            return hashMap.get(key);
        } finally {
            readlock.unlock();
        }
    }

    //设置key对应的value 并返回旧的value
    public static final Object set(String key, Object value) {
        writelock.lock();
        try {
            return hashMap.put(key, value);
        } finally {
            writelock.unlock();
        }
    }

    //清空所有的内容
    public static final void clear() {
        writelock.lock();
        try {
            hashMap.clear();
        }finally {
            writelock.unlock();
        }
    }

}
